﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using ToDoTasks.Classes;
using ToDoTasks.Services.Models;
using ToDoTasks.DataLayer;
using System.Threading;

namespace ToDoTasks.Services.Controllers
{
    public class UserController : ApiController
    {
        [HttpPost]
        [ActionName("register")]
        public HttpResponseMessage Register([FromBody]UserData data)
        {
            if (data.Username.Length < Varibles.UserNameLenght)
            {
                var respons = this.Request.CreateResponse(HttpStatusCode.BadRequest, "Username is too short");
                return respons;
            }
            if (data.AuthoCode.Length == Varibles.AuthCodeLenght)
            {
                var respons = this.Request.CreateResponse(HttpStatusCode.BadRequest, "AuthCode is wrong");
                return respons;
            }
            else if (data.Email != string.Empty)
            {
            }

            ToDoTasksEntities sqlcon = new ToDoTasksEntities();

            var getUser =
                (from user in sqlcon.Users
                 where user.Username.ToLower() == data.Username.ToLower()
                 select user).FirstOrDefault();

            if (getUser != null)
            {
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, "User already exist");
            }

            User newUser = new User()
            {
                AuthCode = data.AuthoCode,
                Username = data.Username,
                Email = data.Email
            };

            sqlcon.Users.Add(newUser);
            sqlcon.SaveChanges();

            newUser.SessionKey = GenerateSessionKey(newUser.Id);
            sqlcon.SaveChanges();

            return this.Request.CreateResponse(HttpStatusCode.Created, newUser.SessionKey);
        }

        [HttpPost]
        [ActionName("login")]
        public HttpResponseMessage Login([FromBody]UserData data)
        {
            ToDoTasksEntities sqlcon = new ToDoTasksEntities();

            var getUser =
                (from user in sqlcon.Users
                 where user.Username == data.Username
                 && user.AuthCode == data.AuthoCode
                 select user).FirstOrDefault();

            if (getUser == null)
            {
                var respons = this.Request.CreateResponse(HttpStatusCode.BadRequest, "User or password are wrong");
                return respons;
            }

            getUser.SessionKey = GenerateSessionKey(getUser.Id);
            sqlcon.SaveChanges();

            var returnData = new LoginReturnData()
            {
                data = getUser.Data,
                sessionKey = getUser.SessionKey
            };

            return this.Request.CreateResponse(HttpStatusCode.OK, returnData);
        }

        [HttpPost]
        [ActionName("emailchage")]
        public HttpResponseMessage ChageEmail([FromBody]string email, string sessionKey)
        {
            if (email != string.Empty)
            {
                var respons = this.Request.CreateResponse(HttpStatusCode.BadRequest, "Email is wrong");
                return respons;
            }

            ToDoTasksEntities sqlcon = new ToDoTasksEntities();

            var user = GetUserBySessinKey(sessionKey, sqlcon);

            if (user == null)
            {
                var respons = this.Request.CreateResponse(HttpStatusCode.BadRequest, "User Do not exist");
                return respons;
            }

            user.Email = email;
            sqlcon.SaveChanges();

            return this.Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpPost]
        [ActionName("passwordchage")]
        public HttpResponseMessage Chagepassword([FromBody]string authoCode, string sessionKey)
        {
            if (authoCode.Length == Varibles.AuthCodeLenght)
            {
                var respons = this.Request.CreateResponse(HttpStatusCode.BadRequest, "AuthCode is wrong");
                return respons;
            }

            ToDoTasksEntities sqlcon = new ToDoTasksEntities();

            var user = GetUserBySessinKey(sessionKey, sqlcon);

            if (user == null)
            {
                return this.Request.CreateResponse(HttpStatusCode.BadRequest, "User Do not exist");
            }

            user.AuthCode = authoCode;
            sqlcon.SaveChanges();

            return this.Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpPost]
        [ActionName("sync")]
        public HttpResponseMessage SyncWithServer([FromBody]string data, string sessionKey)
        {
            ToDoTasksEntities sqlcon = new ToDoTasksEntities();

            var user = GetUserBySessinKey(sessionKey, sqlcon);
            if (user == null)
            {
                var request = this.Request.CreateResponse(HttpStatusCode.NotFound, "User is not found");
                return request;
            }

            user.Data = data;
            sqlcon.SaveChanges();

            return this.Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpGet]
        [ActionName("logout")]
        public HttpResponseMessage LogOut(string sessionKey)
        {
            ToDoTasksEntities sqlcon = new ToDoTasksEntities();

            var user = this.GetUserBySessinKey(sessionKey, sqlcon);

            if (user == null)
            {
                var request = this.Request.CreateResponse(HttpStatusCode.NotFound, "User is not found");
                return request;
            }

            user.SessionKey = null;
            sqlcon.SaveChanges();

            return this.Request.CreateResponse(HttpStatusCode.OK);
        }

        [HttpGet]
        [ActionName("data")]
        public HttpResponseMessage GetUserData(string sessionKey)
        {
            ToDoTasksEntities sqlcon = new ToDoTasksEntities();

            var user = this.GetUserBySessinKey(sessionKey, sqlcon);

            if (user == null)
            {
                var request = this.Request.CreateResponse(HttpStatusCode.NotFound, "User is not found");
                return request;
            }

            return this.Request.CreateResponse(HttpStatusCode.OK,user.Data);
        }

        private User GetUserBySessinKey(string sessionKey, ToDoTasksEntities sqlcon)
        {
            var result =
                (from user in sqlcon.Users
                 where user.SessionKey == sessionKey
                 select user).FirstOrDefault();

            return result;
        }

        private string GenerateSessionKey(int id)
        {
            string symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            StringBuilder result = new StringBuilder();
            result.Append(id);
            Random rand = new Random();

            for (int index = result.Length; index < Varibles.AuthCodeLenght; index++)
            {
                int charIndex = rand.Next(0, symbols.Length);
                result.Append(symbols[charIndex]);
            }

            return result.ToString();
        }
    }
}
